//
//  HistroyShareCardController.m
//  QRMaster
//
//  Created by myApple on 15/7/31.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "HistroyShareCardController.h"
#import "MJRefresh.h"
#import "RecodeShareCardModel.h"
#import "RecoderShareCardCell.h"
#import "Reachability.h"
#import "PromptInfoView.h"
#import "RequestNetWork.h"
#import "EditTimeController.h"
//#import "StartPageController.h"
#import "MJExtension.h"

@interface HistroyShareCardController ()<UITableViewDataSource,UITableViewDelegate>
{
    UITableView * histroyShareCardTableView;
    NSMutableArray * histroyShareCardArray;
    MJRefreshHeader * _headerView;
    UIActivityIndicatorView * _activityIndicator;
    UIImageView * promtBackView;
    //多语言
    UILabel * titleNameLabel;
    UILabel * promtLabel;
}

@end

@implementation HistroyShareCardController

- (void)viewDidLoad {
    [super viewDidLoad];
    histroyShareCardArray = [[NSMutableArray alloc]init];
    self.view.backgroundColor = RGBA(237, 238, 241, 1);
    [self prepareTableView];
//    [self prepareData];
    // Do any additional setup after loading the view.
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self prepareData];
    titleNameLabel.text = NSLocalizedString(@"histroyShare", nil);
    promtLabel.text = NSLocalizedString(@"clickRefresh", nil);
    self.navigationItem.title=NSLocalizedString(@"histroyShare", nil);
}

-(void)preparePromtView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight - 64;
    promtBackView = [[UIImageView alloc]initWithFrame:CGRectMake(x,y, width, height)];
    promtBackView.backgroundColor = RGBA(237, 238, 241, 1);
    promtBackView.userInteractionEnabled = YES;
    promtBackView.hidden = YES;
    [self.view addSubview:promtBackView];
    UITapGestureRecognizer * imgViewTap  = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backViewClick:)];
    [promtBackView addGestureRecognizer:imgViewTap];
    
    x = 0;
    width = ScreenWidth;
    y = ScreenHeight / 2.0 - 10;
    height = 20;
    promtLabel = [[UILabel alloc]initWithFrame:CGRectMake(x, y, width, height)];
    promtLabel.text = NSLocalizedString(@"clickRefresh", nil);
    promtLabel.textColor = RGBA(143, 147, 148, 1);
    promtLabel.textAlignment = NSTextAlignmentCenter;
    [promtBackView addSubview:promtLabel];
    
}

-(void)backViewClick:(UITapGestureRecognizer *)tap
{
    promtBackView.hidden = YES;
    [self prepareData];
}


-(void)prepareData
{
    if ([self IsHaveNetwork]) {
        [histroyShareCardTableView.mj_header endRefreshing];
        return;
    }
    [_activityIndicator startAnimating];
    [self startWaiting:nil color:nil addToView:self.view];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:@"0" forKey:@"today"];
    [rnk initWithPath:POST(NEWSHARELIST) params:postDict block:^(id downLoadData, id error) {
        [self stopWaiting];
        if ([downLoadData objectForKey:@"data"] != nil) {
            [histroyShareCardArray removeAllObjects];
            for (NSDictionary * dict in [downLoadData objectForKey:@"data"]) {
                RecodeShareCardModel * model = [[RecodeShareCardModel alloc]init];
                model = [RecodeShareCardModel mj_objectWithKeyValues:dict];
                model.shareId = [dict objectForKey:@"id"];
                [histroyShareCardArray addObject:model];
            }
            if (histroyShareCardArray.count == 0) {
                promtBackView.hidden = NO;
                [PromptInfoView showMessage:NSLocalizedString(@"noShareList", nil)];
            }
        }
        else if (error != nil) {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
//        [_headerView endRefreshing];
//        [_activityIndicator stopAnimating];
        [histroyShareCardTableView.mj_header endRefreshing];
        [histroyShareCardTableView reloadData];
    }];
}


-(void)prepareTableView
{
    histroyShareCardTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    histroyShareCardTableView.dataSource = self;
    histroyShareCardTableView.delegate = self;
    histroyShareCardTableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:histroyShareCardTableView];
    histroyShareCardTableView.mj_header = [MJRefreshHeader headerWithRefreshingBlock:^{
        [self prepareData];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return histroyShareCardArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * string = @"cell";
    RecoderShareCardCell * cell = [tableView dequeueReusableCellWithIdentifier:string];
    if (!cell) {
        cell = [[RecoderShareCardCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:string];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    RecodeShareCardModel * model = histroyShareCardArray[indexPath.row];
    cell.communityName = model.communityName;
    cell.communityId = model.communityId;
    cell.bulidingName = model.buildName;
    cell.floorName = model.floorName;
//    cell.roomId = model.roomId;
    if ([model.areaCode isEqualToString:_userAreaCode]) {
        cell.shareMobile = model.mobile;
    }
    else
    {
        cell.shareMobile = [NSString stringWithFormat:@"+%@ %@",model.areaCode,model.mobile];
    }
    cell.roomName = model.roomName;
    cell.beginTime = model.startTime;
    cell.endTime = model.endTime;
    cell.shareId = model.shareId;
    cell.status = model.status;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecodeShareCardModel * model = histroyShareCardArray[indexPath.row];
    if (model.status == 1) {
        EditTimeController * etvc = [[EditTimeController alloc]init];
        etvc.communityId = model.communityId;
//        etvc.roomId = model.roomId;
        etvc.beginTime = model.startTime;
        etvc.endTime = model.endTime;
        etvc.shareId = model.shareId;
        [self.navigationController pushViewController:etvc animated:YES];
    }
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecodeShareCardModel * model = histroyShareCardArray[indexPath.row];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    RequestNetWork * rnk = [[RequestNetWork alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:model.shareId forKey:@"shareId"];
    [postDict setValue:model.communityId forKey:@"communityId"];
    [rnk initWithPath:POST(DELETESHARE) params:postDict block:^(id downLoadData, id error) {
        if ([downLoadData objectForKey:@"data"] != nil)
        {
            [histroyShareCardArray removeObjectAtIndex:indexPath.row];
            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationTop];
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }

    }];
//    [rnk initWithPath:POST(DELETESHARE) params:postDict];
//    rnk.resultblock = ^(id data,id error)
//    {
//        if (data != nil)
//        {
//            [histroyShareCardArray removeObjectAtIndex:indexPath.row];
//            [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationTop];
//        }
//        else
//        {
//            if ([[error objectForKey:@"status"]integerValue] == 288) {
//                StartPageController * spc = [[StartPageController alloc]init];
//                [self presentViewController:spc animated:YES completion:^{
//                    [PromptInfoView showMessage:NSLocalizedString(@"errorToken", nil)];
//                }];
//            }
//            else
//            {
//                [PromptInfoView showMessage:[error objectForKey:@"info"]];
//            }
//        }
//    };

}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RecodeShareCardModel * model = histroyShareCardArray[indexPath.row];
    if (model.status == 1) {
        return NSLocalizedString(@"deleteCell", nil);
    }
    else
    {
        return NSLocalizedString(@"delete", nil);
    }
}

//#pragma mark --- MJRefreshDelegate
//-(void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
//{
//    [self prepareData];
//}


//初始化风火轮
-(void)prepareActivityIndicator
{
    _activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activityIndicator.frame = CGRectMake(self.view.frame.size.width / 2.0 -15, self.view.frame.size.height / 2.0 - 15, 30, 30);
    _activityIndicator.hidden = NO;
    [self.view addSubview:_activityIndicator];
}


//判断是否有网络
-(BOOL)IsHaveNetwork
{
    Reachability * reach = [Reachability reachabilityForInternetConnection];
    if([reach currentReachabilityStatus] == NotReachable) {
        [PromptInfoView showMessage:NSLocalizedString(@"noNetWork", nil)];
        return YES;
    }
    return NO;
}

-(void)dealloc
{
//    [_headerView free];
}



-(void)BackClick
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
